<template>
    <el-container class="gird">
        <el-header ref="header" :class="column?'column':''">
            <div>
                <ChfToolbar :toolbarConfig="toolbarConfig">
                    <template #[item.slotName] v-for="item in toolbarSlotList">
                        <slot :name="[item.slotName]"></slot>
                    </template>
                </ChfToolbar>
            </div>
            <div>
                <ChfForm v-bind="formConfig" v-model="formConfig.form" @submit="submit"></ChfForm>
            </div>
        </el-header>
        <el-main>
            <el-table v-bind="tableConfig.options" v-loading="loading" :style="{width:tableConfig.options.width?`${tableConfig.options.width}px`:`100%`}"
                v-on="tableConfig.events" ref="table">
                <template v-for="(item,i) in tableConfig.columns">
                    <gird-column :columns="item" :key="i">
                        <template #[item.slotName]="{row}" v-if="item.slotName">
                            <slot :name="[item.slotName]" :row="row" :item="item"></slot>
                        </template>
                        <template #[item.headerSlotName]="{scope}" v-if="item.headerSlotName">
                            <slot :name="[item.headerSlotName]" :scope="scope" :item="item"></slot>
                        </template>
                    </gird-column>
                </template>
            </el-table>
        </el-main>
        <el-footer>
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" v-bind="pagerConfig.options" v-on="pagerConfig.options.events">
            </el-pagination>
        </el-footer>
    </el-container>
</template>


<script>
import girdColumn from "./girdColumn.vue";
import ChfToolbar from "../chf-toolbar/index.vue"

// 监听页面元素宽度和高度变化
// import elementResizeDetectorMaker from "element-resize-detector";
export default {
    data () {
        return {
            column: false,
            loading: false,
            tableDefault: {
                options: {
                    border: true,
                    ['header-cell-style']: { textAlign: 'center' },
                    ['cell-style']: { textAlign: 'center' },
                    ['row-key']: "id"
                    // ['element-loading-text']:"拼命加载中",
                    // ['element-loading-spinner']:"el-icon-loading",
                    // ['element-loading-background']:"rgba(0, 0, 0, 0.8)"
                    // width:800,
                    // height:250,
                    // stripe:true,
                    // ['highlight-current-row']:true,
                    // rowKey:"id",
                    // treeProps:{children: 'children', hasChildren: 'hasChildren'},
                    // lazy:true,
                    // showSummary:true,
                    // sumText:'总计',
                    // summaryMethod:(param)=>{
                    //     return ['总价',null,10,10,10,10,10,10,10]
                    // },
                    // load:(tree,treeNode,resolve)=>{
                    //     console.log(tree);
                    //     console.log(treeNode);
                    //     setTimeout(() => {
                    //         resolve([
                    //             {
                    //                 id:tree.id*10,
                    //                 name: "王小虎",
                    //                 nickname: "小虎",
                    //                 age: 11,
                    //                 sex: 1,
                    //                 province: "湖北省",
                    //                 city: "武汉市",
                    //                 area: "洪山区",
                    //             },
                    //             {
                    //                 id:tree.id*11,
                    //                 name: "王小虎",
                    //                 nickname: "小虎",
                    //                 age: 11,
                    //                 sex: 1,
                    //                 province: "湖北省",
                    //                 city: "武汉市",
                    //                 area: "洪山区",
                    //             }
                    //         ])
                    //         }, 1000)
                    // },
                    // rowClassName:({row, rowIndex})=>{
                    //     if (rowIndex === 1) {
                    //         return 'warning-row';
                    //         } else if (rowIndex === 3) {
                    //         return 'success-row';
                    //     }
                    //         return '';
                    // },
                    // ['span-method']:({ row, column, rowIndex, columnIndex })=>{
                    //    if (columnIndex === 0) {
                    //         if (rowIndex % 2 === 0) {
                    //                 return {
                    //                     rowspan: 2,
                    //                     colspan: 1
                    //                 };
                    //             } else {
                    //                 return {
                    //                 rowspan: 0,
                    //                 colspan: 0
                    //             };
                    //         }
                    //    }
                    // },
                },
            },
            pagerDefault: {
                pageSize: 10,
                currentPage: 1,
                pageSizes: [10, 20, 30, 40],
                total: 0,
                layout: "total, sizes, prev, pager, next, jumper",
                // hideOnSinglePage:true,
            },
            proxyDefault: {},
            column: false
        };
    },
    props: {
        //表格配置
        tableConfig: {
            type: Object,
            default: () => {
                return {};
            },
        },
        //分页配置
        pagerConfig: {
            type: Object,
            default: () => {
                return {};
            },
        },
        //请求配置
        proxyConfig: {
            type: Object,
            default: () => {
                return {};
            },
        },
        //过滤条件配置
        formConfig: {
            type: Object,
            default: () => {
                return {};
            },
        },
        //工具栏配置
        toolbarConfig: {
            type: Array,
            default: () => []
        }
    },
    created () {
        // 初始化
        this.init();
    },
    mounted () {
        const myObserver = new ResizeObserver(entries => {
            entries.forEach(entry => {
                if (entry.target.offsetHeight > 60) {
                    this.column = true
                } else {
                    this.column = false

                }
            })
        })
        myObserver.observe(this.$refs.header.$el)
        this.$once('hook:beforeDestroy', () => {
            myObserver.unobserve(this.$refs.header.$el)
        })

    },
    methods: {
        submit (form) {
            this.pagerConfig.options.currentPage = 1;
            this.formConfig.form = form;
            console.log(this.formConfig.form);
            this.getDataList();
        },
        // 初始化默认数据
        init () {
            // 默认table配置
            Object.keys(this.tableDefault.options).forEach((item) => {
                if (!this.tableConfig.options[item]) {
                    this.tableConfig.options[item] = this.tableDefault.options[item];
                }
            });
            // 默认Pagination配置
            if (this.pagerConfig.options) {
                Object.keys(this.pagerDefault).forEach((item) => {
                    if (!this.pagerConfig.options[item]) {
                        if (item === "pageSizes" && this.pagerConfig.options.pageSize && !this.pagerConfig.options.pageSizes) {
                            this.pagerConfig.options[item] = [
                                this.pagerConfig.options.pageSize,
                                this.pagerConfig.options.pageSize * 2,
                                this.pagerConfig.options.pageSize * 4,
                                this.pagerConfig.options.pageSize * 8,
                            ];
                        } else {
                            this.pagerConfig.options[item] = this.pagerDefault[item];
                        }
                    }
                });
            } else {
                this.pagerConfig.options = this.pagerDefault
            }

            this.getDataList();
        },
        async getDataList () {
            if (this.proxyConfig.api) {
                this.loading = true;
                try {
                    let params = {
                        limit: this.pagerConfig.options.pageSize,
                        page: this.pagerConfig.options.currentPage,
                        ...this.formConfig.form,
                    };
                    // 请求前
                    if (this.proxyConfig.beforeQuery) {
                        params = await this.proxyConfig.beforeQuery(params)
                    }
                    console.log(params)
                    if (params !== false) {
                        const { result } = await this.$api[this.proxyConfig.api](params);
                        this.tableConfig.options.data = result.records;
                        console.log(this.tableConfig.options.data);
                        this.pagerConfig.options.total = result.total;
                        //请求后
                        this.proxyConfig?.callback?.(result, params);
                    }
                    this.loading = false;
                } catch (error) {
                    this.loading = false;
                }
            }
        },
        // pageSize 改变时会触发
        handleSizeChange (val) {
            this.pagerConfig.options.currentPage = 1;
            this.pagerConfig.options.pageSize = val;
            this.getDataList();
        },
        // pageIndex 改变时会触发
        handleCurrentChange (val) {
            this.pagerConfig.options.currentPage = val;
            this.getDataList();
        },
        //用来给新增删除后重新请求接口
        getData () {
            this.pagerConfig.options.currentPage = 1;
            this.getDataList();
        },
        //用来清除选中
        clearSelection () {
            this.$refs.table.clearSelection();
        }
    },
    computed: {
        toolbarSlotList () {
            console.log(this.toolbarConfig.filter(item => item.slotName));
            return this.toolbarConfig.filter(item => item.slotName)
        }
    },
    components: {
        girdColumn,
        ChfToolbar
    },
};
</script>

<style lang="scss" scoped>
.grid {
    background: white;
}

.el-footer {
    display: flex;
    justify-content: center;
    align-items: center;
}

.column {
    & > div {
        flex: 1;
        order: 1;
    }
    & > div:last-child {
        order: 0;
        flex: none;
        text-align: right;
    }
}

.el-header {
    height: auto !important;
    min-height: 60px;
    padding: 0 0 10px 0;
    display: flex;
    justify-content: flex-end;
    flex-wrap: wrap;

    ::v-deep .el-form-item {
        margin-bottom: 0;
    }
    & > div {
        margin-top: 10px;
        flex: 1;
    }
    & > div:last-child {
        flex: none;
        text-align: right;
        width: auto;
    }
}

.el-main {
    padding: 0;
}
</style>

<style >
.el-table .warning-row {
    background: oldlace;
}

.el-table .success-row {
    background: #f0f9eb;
}

.el-table__row {
    cursor: pointer;
}
</style>